from pyquery import PyQuery as pq
import time
from tool import dbconfig,Db,mylog,get_html
import datetime
'''
下载每天的直播数据
每隔5分钟运行一次
'''
def parseurl():
    url = "https://www.zhiball.com/"
    html_content = get_html(url)
    doc = pq(html_content)
    date_items = doc(".onstatus li").items()
    datalist = []
    for item in date_items:
        cup_title = item.find(".league").text().strip()
        mdHi = item.find(".time").text().strip()
        ha = item.find(".game").text().strip()
        #用VS分割ha , 并判断是否能分割
        home = ''
        away = ''
        if(ha.find('VS') != -1):
            home = ha.split('VS')[0].strip()
            away = ha.split('VS')[1].strip()
        score = item.find("span.bf").text().strip()
        home_score = ''
        away_score = ''
        if(score.find('VS') != -1):
            home_score = score.split('VS')[0]
            away_score = score.split('VS')[1]
        #当前年份
        year = datetime.date.today().year
        curtime = str(year) + '-' + mdHi
        ts =  time.mktime(time.strptime(curtime , "%Y-%m-%d %H:%M"))
        ts = int(ts)
        #年月日
        ymd = time.strftime("%Y-%m-%d" , time.localtime(ts))
        #时分
        hi = time.strftime("%H:%M" , time.localtime(ts))
        datalist.append((ha , cup_title , home , away , home_score , away_score , ymd , hi , ts))
    return datalist

def savedb(datalist = []):
    db = Db(config=dbconfig)
    for item in datalist:
        sql = 'select count(id) as num from mf_livedata where ha="%s" and cup_title="%s" and ymd="%s" and hi="%s" and ts=%d' % (item[0] , item[1] , item[6] , item[7] , item[8])
        data = db.getdata(sql)
        if(data[0]['num'] <= 0):
            db.exe_sql('insert into mf_livedata(ha , cup_title , home , away , home_score , away_score , ymd , hi , ts) values("%s","%s","%s","%s","%s","%s","%s","%s",%d)' % item)
        else:
            db.exe_sql('update mf_livedata set home_score="%s" , away_score="%s" where ha="%s" and cup_title="%s" and ymd="%s" and hi="%s" and ts=%d' % (item[4] , item[5] , item[0] , item[1] , item[6] , item[7] , item[8]))
    db.close()
    mylog('直播数据插入成功' , 'everyday.log')

def main():
    try:
        datalist = parseurl()
        #print(datalist)
        savedb(datalist)
        print('直播数据插入成功')
    except Exception as err:
        mylog("直播数据插入失败 : " + str(err), 'everyday.log')
        # myprint("error : " + str(err))

'''
每隔6个小时执行一次
下载每日直播数据
'''
if(__name__ == '__main__'):

    main()